function isMobileOrTabletInPortrait() {
  const mobileRegex = /iphone|ipod|android.*mobile|huawei.*phone|xiaomi.*phone|oppo.*phone|vivo.*phone/i
  const tabletRegex = /ipad|tablet|windows\s+tablet|microsoft\s+surface|huawei.*tab|samsung.*tab|lg.*tab|asus.*tab|meizu.*pad|xiaomi.*pad|oppo.*pad|vivo.*pad/i
  const userAgent = navigator.userAgent.toLowerCase()
  let isMobile = mobileRegex.test(userAgent)
  let isTablet = !isMobile && tabletRegex.test(userAgent)
  const isPortrait = window.matchMedia("(orientation: portrait)").matches
  return isMobile || (isTablet && isPortrait)
}

function setRootFontSize() {
  var isMobile = isMobileOrTabletInPortrait()
  var windowWidth = window.innerWidth
  var windowHeight = window.innerHeight
  var rootElement = document.getElementById("root")
  if (!isMobile) {
    if (windowWidth > windowHeight) {
      document.body.style.backgroundColor = "#eee"
      if (rootElement) {
        rootElement.style.cssText = "max-width: 640px; min-height: 100vh; background-color: #fff; margin: 0 auto; position: relative;"
      }
    } else {
      document.body.style.backgroundColor = ""
      if (rootElement) {
        rootElement.style.cssText = ""
      }
    }
  }
  var clientWidth = rootElement ? rootElement.offsetWidth : windowWidth
  var fontSize = 75 * (clientWidth / 750)
  document.documentElement.style.fontSize = fontSize + "px"
}

function debounce(func, delay) {
  let timer
  return function (...args) {
    clearTimeout(timer)
    timer = setTimeout(() => func.apply(this, args), delay)
  }
}

document.addEventListener("DOMContentLoaded", () => {
  window.addEventListener("orientationchange", debounce(setRootFontSize, 150))
})
window.addEventListener("resize", debounce(setRootFontSize, 150))
setRootFontSize()
